package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.job.*;
import jd.union.open.goods.promotiongoodsinfo.query.response.UnionOpenGoodsPromotiongoodsinfoQueryResponse;
import jd.union.open.order.query.response.OrderResp;
import jd.union.open.order.query.response.SkuInfo;
import jd.union.open.order.query.response.UnionOpenOrderQueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
public class JdOrderDetailServiceJobImpl implements IJdOrderDetailJobService {
    private static final Logger log = LoggerFactory.getLogger(JdOrderDetailServiceJobImpl.class);
    @SuppressWarnings({"unused", "rawtypes"})
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IJdUserOrderService jdUserOrderService;
    @Autowired
    private IJdOrderDetailService jdOrderDetailService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private com.eco.fanliapp.jd.JdOrderController JdOrderController;

    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private AppGeneralfeeschemeMapper appGeneralfeeschemeMapper;
    /**
     * Eco API
     * 拉取订单
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getOrderDetail(Integer pageNo,Integer type,String time) {
        try {
            String str = "";
            UnionOpenOrderQueryResponse jdOrderDetails = JdOrderController.getJDOrderDetails(pageNo, type, time, 50000, 5000);
            if (jdOrderDetails != null) {
                str = JSON.toJSONString(jdOrderDetails);
            }
            //数据封装
            UnionOpenOrderQueryResponse info = JsonUtils.getJsonToBean(str, UnionOpenOrderQueryResponse.class);
            //判断是否有订单
            if (info != null && info.getData() != null && info.getCode() == 200) {
                OrderResp[] data = info.getData();
                for(OrderResp order : data){
                    if(order.getSkuList() != null && order.getSkuList().length > 0){
                        try {
                            //处理单个付款订单
                            log.info("处理订单数据2：{}", JSON.toJSONString(order));
                            SkuInfo[] skuList = order.getSkuList();
                            for(SkuInfo sku:skuList){
                                if(sku.getValidCode() == 15){
                                    continue;
                                }
                                //redis锁-时间
                                long startTimes = System.currentTimeMillis() + 1000 * 60;
                                //获取锁
                                if (!redisLockService.lock(order.getOrderId() + "jdOrder" + sku.getSkuId(), startTimes + "")) {
                                    continue;
                                }
                                //关联用户
                                AppUser appUser = UserMainNew(order);
                                //存订单信息
                                JdOrderDetail jdOrderDetail = dealOrderInfoStep(appUser, order,sku);
                                if(jdOrderDetail != null){
                                    //计算分佣金额
                                    BigDecimal commission = handleJdCommission(jdOrderDetail.getSubUnionId(), jdOrderDetail.getOrderId(),
                                            jdOrderDetail.getSkuId(), jdOrderDetail.getEstimateFee(),jdOrderDetail.getValidCode());
                                    //处理order
                                    handleJdUserOrder(jdOrderDetail.getSubUnionId(),jdOrderDetail.getOrderId(),jdOrderDetail.getSkuId(),
                                            jdOrderDetail.getValidCode(),jdOrderDetail.getFinishTime(),commission,jdOrderDetail.getSkuName());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("京东订单处理出错" + e.getMessage());
                        }
                    }
                }
                //判断是否存在下一页
                if (info.getHasMore()) {
                    getOrderDetail(pageNo, type, time);
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    /**
     * 计算京东用户补贴
     * @param subUnionId
     * @param orderId
     * @param skuId
     * @return
     */
    public BigDecimal handleJdCommission(String subUnionId,Long orderId,Long skuId,BigDecimal estimateFee,int validCode){
        log.info("计算京东用户补贴,用户id：{};订单号：{};商品id：{};联盟佣金：{}",subUnionId,orderId,skuId,estimateFee);
		BigDecimal commission = new BigDecimal("0.00");
        try {
            if(StringUtils.isEmpty(subUnionId)){
                return commission;
            }
            if(validCode < 15){
                return commission;
            }
            log.info("计算京东用户补贴,订单号：{}",orderId);
            //判断order是否存在
            JdUserOrder jdUserOrder = jdUserOrderService.selectByOrderSnAndSkuId(orderId,skuId);
            if(jdUserOrder == null){
                //1.获取人所属公司;2.获取返佣的信息
                AppGeneralFeeScheme generalFeeScheme = appGeneralfeeschemeMapper.selectGeneralFeeScheme(Long.valueOf(subUnionId),2);
                //联盟佣金
                double promotion = estimateFee.doubleValue();
                log.info("计算京东用户补贴,联盟佣金：{}，单位：（元）",promotion);
                //计算补贴金额
                Integer orderScale = null;
                if (generalFeeScheme.getOnepay() >= promotion) {
                    orderScale = generalFeeScheme.getOnepayScale();
                } else if (generalFeeScheme.getTwopay() >= promotion) {
                    orderScale = generalFeeScheme.getTwopayScale();
                } else if (generalFeeScheme.getThirdpay() >= promotion) {
                    orderScale = generalFeeScheme.getThirdpayScale();
                } else if (generalFeeScheme.getForpay() >= promotion) {
                    orderScale = generalFeeScheme.getForpayScale();
                } else if (generalFeeScheme.getFivepay() >= promotion) {
                    orderScale = generalFeeScheme.getFivepayScale();
                } else if (generalFeeScheme.getSixpay() >= promotion) {
                    orderScale = generalFeeScheme.getSixpayScale();
                } else if (generalFeeScheme.getSevenpay() >= promotion) {
                    orderScale = generalFeeScheme.getSevenpayScale();
                }

                log.info("计算京东用户补贴,计算的佣金比率：{}",orderScale);
                //补贴价格
				commission = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), estimateFee);
			}
        } catch (Exception e) {
            e.printStackTrace();
            return commission;
        }
        log.info("计算京东用户补贴,返回的佣金：{}",commission);
        return commission;
    }

    /**
     * 计算京东用户补贴延迟天数
     * @param finishTime
     * @return
     */
    public Long handleDelayTime(Long finishTime){
        //获取设置的延迟天数
        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        Integer delaydays = commissionFreeze.getDelaydays();

        return getDateTime(finishTime,delaydays);
    }

    /**
     * 处理jd订单表（1.分佣；2.延迟天数；3.状态的处理；4.防止重复处理）
     * @param subUnionId
     * @param orderId
     * @param skuId
     * @param validCode
     * @param finishTime
     * @param commission
     */
    public void handleJdUserOrder(String subUnionId,Long orderId,Long skuId,int validCode ,Long finishTime,BigDecimal commission,String skuName){
        log.info("处理jd订单表,用户id：{}；订单编号：{}；商品id：{}；订单状态：{}；延迟时间：{}；用户补贴：{}",subUnionId,orderId,skuId,validCode,finishTime,commission);
		if(StringUtils.isEmpty(subUnionId)){
			return;
		}
        BigDecimal commissionNew = new BigDecimal(0);

        //判断order表是否已存在，有就新增，没有就更新
        JdUserOrder jdUserOrder = jdUserOrderService.selectByOrderSnAndSkuId(orderId,skuId);

        JdUserOrder userOrder = new JdUserOrder();
        if(jdUserOrder == null){
            commissionNew = commission;
            userOrder.setUserId(Long.valueOf(subUnionId));
            userOrder.setOrderId(orderId);
            userOrder.setSkuId(skuId);
            userOrder.setCommission(commission);
            userOrder.setOrderStatus(validCode);
        }else{
            if(jdUserOrder.getOrderStatus() == validCode){
                return;
            }
            if(jdUserOrder.getOrderSettleStatus() == 2){
                if(validCode < 15){
                    handleUserBalance(jdUserOrder.getUserId(),jdUserOrder.getCommission());
                }else{
                    return;
                }
            }
            userOrder.setTableId(jdUserOrder.getTableId());
            userOrder.setOrderStatus(validCode);
            if(validCode < 15){
                userOrder.setCommission(new BigDecimal(0.00));
            }
                commissionNew = jdUserOrder.getCommission();
        }
        //计算大额延迟的时间
        if(validCode > 16){
            Long aLong = handleDelayTime(finishTime);
            userOrder.setLargeAmountTime(aLong);
        }
        boolean b = jdUserOrderService.saveOrUpdate(userOrder);
        if(b){
            if (validCode == 16) {
                sendMsg(subUnionId, NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),commissionNew,skuName);
            }
            if(validCode < 15){
                sendMsg(subUnionId, NewsEnumLog.NEWS_ORDER_FAIL.getNewsType(),commissionNew,skuName);
            }
            if(validCode > 16){
                sendMsg(subUnionId, NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),commissionNew,skuName);
            }
        }
    }
     /**
     * 处理扣钱操作
     * @param userId
     * @param commission
     */
    public void handleUserBalance(Long userId,BigDecimal commission){
        //查询这个账户
        log.info("用户id：{}，需要扣除的佣金",userId,commission);
        try {
            AppUser appUser = iAppUserService.selectAppUserByUserId(userId);
            if(appUser != null){
                double banlance = appUser.getBalance().doubleValue();
                double promotion = commission.doubleValue();
                //扣钱
                double sub = ComputeUtil.sub(banlance, promotion);
                log.info("扣除金额：{}元",sub);
                //更新
                AppUser user = new AppUser();
                user.setTableId(appUser.getTableId());
                user.setBalance(new BigDecimal(sub));
                iAppUserService.updateById(user);

                //添加账户变更日志
                syUserMoneyLogService.addSyUserMoneyLog(appUser.getUserId(), new BigDecimal(banlance), new BigDecimal(promotion), "京东订单补贴扣除", null, 1);
                log.info("京东订单用户id:{},账户变更前余额：{}，账户应扣金额：{},账户变更后余额：{}", appUser.getUserId(), banlance, promotion, sub);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送消息
     * @param subUnionId
     * @param newsType
     * @param commission
     */
    public void sendMsg(String subUnionId, int newsType,BigDecimal commission,String skuName){
        try {
            iAppNewsLogService.newsType(Long.parseLong(subUnionId),newsType,commission, "京东",skuName,commission.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 存订单信息
     *
     * @param appUser
     * @return
     */
    public JdOrderDetail dealOrderInfoStep(AppUser appUser, OrderResp order,SkuInfo sku) {
        JdOrderDetail jdOrderDetail = new JdOrderDetail();
        //数据库中查询该订单
        JdOrderDetail jdOrderDetailDatabase = jdOrderDetailService.selectOrderDetailByOrderId(order.getOrderId(),sku.getSkuId());
        if (jdOrderDetailDatabase != null) {
//            if(sku.getValidCode() == jdOrderDetailDatabase.getValidCode()){
//                return null;
//            }
            jdOrderDetail.setTableId(jdOrderDetailDatabase.getTableId());
            jdOrderDetail.setCreateTime(jdOrderDetailDatabase.getCreateTime());
            jdOrderDetail.setDeleted(jdOrderDetailDatabase.getDeleted());
        }else {
            jdOrderDetail.setCreateTime(new Date());
        }
        jdOrderDetail.setFinishTime(order.getFinishTime());
        jdOrderDetail.setOrderEmt(order.getOrderEmt());
        jdOrderDetail.setOrderId(order.getOrderId());
        jdOrderDetail.setOrderTime(order.getOrderTime());
        jdOrderDetail.setParentId(order.getParentId());
        jdOrderDetail.setPlus(order.getPlus());
        jdOrderDetail.setActualCosPrice(new BigDecimal(sku.getActualCosPrice()));
        jdOrderDetail.setActualFee(new BigDecimal(sku.getActualFee()));
        jdOrderDetail.setCommissionRate(new BigDecimal(sku.getCommissionRate()));
        jdOrderDetail.setEstimateCosPrice(new BigDecimal(sku.getEstimateCosPrice()));
        jdOrderDetail.setEstimateFee(new BigDecimal(sku.getEstimateFee()));
        jdOrderDetail.setFinalRate(new BigDecimal(sku.getFinalRate()));
        jdOrderDetail.setPid(sku.getPid());
        jdOrderDetail.setPositionId(sku.getPositionId());
        jdOrderDetail.setPrice(new BigDecimal(sku.getPrice()));
        jdOrderDetail.setSkuId(sku.getSkuId());
        jdOrderDetail.setSkuName(sku.getSkuName());
        //图片
        jdOrderDetail.setSkuPicture("http://qiniuimage.shengyaapp.com/Fj78u0dm11DvTrBlhP77zQO-txD4");
        jdOrderDetail.setSkuNum(sku.getSkuNum());
        jdOrderDetail.setSkuReturnNum(sku.getSkuReturnNum());
        jdOrderDetail.setSubSideRate(new BigDecimal(sku.getSubSideRate()));
        jdOrderDetail.setSubsidyRate(new BigDecimal(sku.getSubsidyRate()));
        jdOrderDetail.setUnionAlias(sku.getUnionAlias());
        jdOrderDetail.setUnionTag(sku.getUnionTag());
        jdOrderDetail.setValidCode(sku.getValidCode());
        jdOrderDetail.setSubUnionId(sku.getSubUnionId());
        jdOrderDetail.setPayMonth(sku.getPayMonth());
        jdOrderDetail.setPopId(sku.getPopId());
        jdOrderDetail.setExt1(sku.getExt1());
        jdOrderDetail.setUnionId(order.getUnionId());
        jdOrderDetail.setTraceType(sku.getTraceType());
        jdOrderDetail.setUnionTrafficGroup(sku.getUnionTrafficGroup());
        jdOrderDetail.setSiteId(sku.getSiteId());
        if (StringUtils.isEmpty(appUser)) {
            log.info( "订单关联不到用户,order={}", order.getOrderId());
            boolean b = jdOrderDetailService.saveOrUpdate(jdOrderDetail);
            if (b) {
                log.info("订单关联不到用户{}已经处理了", jdOrderDetail.getOrderId());
            }
        } else {
            if (jdOrderDetail == null) {
                boolean b = jdOrderDetailService.saveOrUpdate(jdOrderDetail);
                log.info("订单{}入库-result={}", jdOrderDetail.getOrderId(), b);
            } else {
                boolean b = jdOrderDetailService.saveOrUpdate(jdOrderDetail);
                log.info("订单{}入库-result={}", jdOrderDetail.getOrderId(), b);
            }
        }
        return jdOrderDetail;
    }

    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMainNew(OrderResp order) {
        AppUser appUser = null;
//        QueryWrapper<JdUserOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("order_id", order.getOrderId() + "");
//        JdUserOrder jdUserOrder = jdUserOrderService.getOne(queryWrapper);
//        if (jdUserOrder != null && jdUserOrder.getUserId() != null) {
//            appUser = iAppUserService.selectAppUserByUserId(jdUserOrder.getUserId());
//        }
        if (appUser == null) {
            String subUnionId = null;
            SkuInfo[] skuList = order.getSkuList();
            for(SkuInfo sku :skuList){
                subUnionId = sku.getSubUnionId();
            }
            appUser = iAppUserService.selectAppUserByUserId(Long.parseLong(subUnionId));
        }
        return appUser;
    }

    public String generateOrderDetailId(String childOrderId, String itemId) {
        return MD5Utils.createMD5(itemId + childOrderId);
    }


    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Long earningTime,Integer start) {
        Date paramDate = null;
        if(earningTime == null){
            paramDate = new Date();
        }else{
            paramDate = new Date(earningTime);
        }
        return org.apache.commons.lang3.time.DateUtils.addDays(paramDate, start).getTime();
    }





    private CountLauncherPay countLauncherPay;

    private CountLauncherFail countLauncherFail;

    private CountLauncherSuccess countLauncherSuccess;

    private CountLauncherDone countLauncherDone;

    private CountLauncherRefund countLauncherRefund;

    @Override
    public CountLauncherPay getCountLauncherPay() {
        return countLauncherPay;
    }

    @Override
    public void setCountLauncherPay(CountLauncherPay countLauncherPay) {
        this.countLauncherPay = countLauncherPay;
    }

    @Override
    public CountLauncherFail getCountLauncherFail() {
        return countLauncherFail;
    }

    @Override
    public void setCountLauncherFail(CountLauncherFail countLauncherFail) {
        this.countLauncherFail = countLauncherFail;
    }

    @Override
    public CountLauncherSuccess getCountLauncherSuccess() {
        return countLauncherSuccess;
    }

    @Override
    public void setCountLauncherSuccess(CountLauncherSuccess countLauncherSuccess) {
        this.countLauncherSuccess = countLauncherSuccess;
    }

    @Override
    public CountLauncherDone getCountLauncherDone() {
        return countLauncherDone;
    }

    @Override
    public void setCountLauncherDone(CountLauncherDone countLauncherDone) {
        this.countLauncherDone = countLauncherDone;
    }

    @Override
    public CountLauncherRefund getCountLauncherRefund() {
        return countLauncherRefund;
    }


    @Override
    public void setCountLauncherRefund(CountLauncherRefund countLauncherRefund) {
        this.countLauncherRefund = countLauncherRefund;
    }
}
